<template>
  <div class="ai-search-container">
    <div class="main-wrapper">
      <div class="header">
        <div class="title">
          <i class="el-icon-s-opportunity"></i>
          <h1>AI 中国音网搜索助手</h1>
          <span class="beta-tag">Beta版</span>
        </div>
      </div>
      <div class="search-box">
        <div class="search-show" v-show="!showAnswer">
          <div class="search-title">输入描述，开始检索</div>
          <div class="input-wrapper">
            <el-input
              type="textarea"
              placeholder="简要描述你想搜索的音乐"
              v-model="inputVal"
              :autosize="{ minRows: 13, maxRows: 13 }"
            >
            </el-input>
            <div class="send-icon" @click="sendMessage">
              <img src="../../assets/img/icons/sending.png" alt="send" />
            </div>
          </div>
          <div class="preset-questions">
            <div class="question-header">
              <span>试试这个</span>
              <el-button type="text">
                <i class="el-icon-refresh"></i>
              </el-button>
            </div>
            <div class="questions-list">
              <div
                v-for="(question, index) in presetQuestions"
                :key="index"
                class="question-item"
                @click="handlePresetQuestion(question)"
              >
                <i class="el-icon-chat-dot-square"></i>
                {{ question }}
              </div>
            </div>
          </div>
        </div>

        <div class="chat-container" v-show="showAnswer">
          <div class="message-list">
            <div
              v-for="(msg, index) in messages"
              :key="index"
              class="message-item"
              :class="{
                'user-message': msg.role === 'user',
                'ai-message': msg.role === 'ai',
              }"
            >
              <div
                v-if="msg.role === 'user'"
                class="message-header user-header"
              >
                <img src="../../assets/img/icons/quesIcon.png" alt="user" />
                <span>{{ msg.content }}</span>
              </div>

              <div v-if="msg.role === 'ai'" class="message-content">
                <div class="thinking-header">
                  <img src="../../assets/img/icons/lightIcon.png" alt="ai" />
                  <div class="thinking">深度思考</div>
                </div>
                <div class="answer-text">{{ msg.thinking }}</div>
                <div
                  class="formal-answer"
                  v-html="renderMarkdown(msg.answer)"
                ></div>
              </div>
            </div>
          </div>
          <div class="ai-input-wrapper">
            <el-input
              v-model="followUpInput"
              placeholder="继续提问..."
              @keyup.enter.native="handlePresetQuestion(followUpInput)"
            >
              <template #suffix>
                <img
                  src="../../assets/img/icons/sending.png"
                  alt="send"
                  class="send-icon"
                  @click="handlePresetQuestion(followUpInput)"
                />
              </template>
            </el-input>
          </div>
        </div>
      </div>
    </div>
    <div class="footer-text">内容由 AI 生成，请仔细甄别</div>
  </div>
</template>

<script>
const MarkdownIt = require("markdown-it");
import DOMPurify from "dompurify";

export default {
  name: "AiSearch",
  data() {
    return {
      inputVal: "",
      showAnswer: false,
      deepThinking: "",
      formalAnswer: "",
      messages: [],
      presetQuestions: [
        "有哪些知名四大名著有关的音乐？",
        "介绍一下中国古典音乐的特点",
        "推荐一些经典的民族音乐作品",
        "中国传统乐器都有哪些？",
      ],
      followUpInput: "",
    };
  },
  methods: {
    sendMessage() {
      if (!this.inputVal.trim()) return;
      this.showAnswer = true;

      // 添加用户消息
      this.messages.push({
        role: "user",
        content: this.inputVal.trim(),
        thinking: "",
        answer: "",
      });

      // 添加AI消息占位
      this.messages.push({
        role: "ai",
        content: "",
        thinking: "",
        answer: "",
      });

      const aiIndex = this.messages.length - 1;

      fetch(
        `/front/deepseek/stream?question=${encodeURIComponent(
          this.inputVal.trim()
        )}`,
        {
          method: "GET",
          headers: {
            contentType: "application/json;charset=UTF-8",
            databaseCode: "YINWANG",
            installationId: "installationId",
            token: "",
          },
        }
      )
        .then(async (res) => {
          const reader = res.body.getReader();
          const decoder = new TextDecoder();
          try {
            let isCollectingThinking = false;
            let isCollectingAnswer = false;
            while (true) {
              const { done, value } = await reader.read();
              if (done) break;

              const text = decoder.decode(value, { stream: true });
              const currentMessage = this.messages[aiIndex];

              if (isCollectingThinking) {
                if (text.includes("以下是AI回答")) {
                  isCollectingThinking = false;
                  isCollectingAnswer = true;
                  currentMessage.answer += text.replace(/<br\s*\/?>/gi, "");
                } else {
                  currentMessage.thinking += text;
                }
              } else if (isCollectingAnswer) {
                currentMessage.answer += text.replace(/<br\s*\/?>/gi, "");
              } else {
                isCollectingThinking = true;
                currentMessage.thinking += text.replace(/^深度思考：/g, "");
              }

              // 触发视图更新
              this.$set(this.messages, aiIndex, { ...currentMessage });
            }
          } catch (error) {
            console.error("Error reading stream:", error);
            this.displayedMessage = "获取回答出错，请重试";
          }
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
          this.displayedMessage = "获取回答出错，请重试";
        });
    },
    handlePresetQuestion(question) {
      this.inputVal = question;
      this.sendMessage();
      this.followUpInput = "";
    },
    renderMarkdown(content) {
      const md = new MarkdownIt();
      const dirtyHtml = md.render(content);
      return DOMPurify.sanitize(dirtyHtml);
    },
  },
  watch: {
    messages: {
      handler() {
        this.$nextTick(() => {
          const container = this.$refs.messageList;
          if (container) {
            // 检测是否接近底部（距离底部50像素内视为触底）
            const isNearBottom =
              container.scrollHeight -
                container.clientHeight -
                container.scrollTop <=
              50;

            // 当处于底部区域时自动滚动
            if (isNearBottom) {
              container.scrollTop = container.scrollHeight;
            }
          }
        });
      },
      deep: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.answerBox {
  margin-top: 20px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;

  .answer-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    background-color: #2563eb;
    height: 34px;
    padding: 0 12px;
    border-radius: 4px;

    img {
      margin-right: 12px;
    }

    span {
      font-size: 14px;
      color: #fff;
    }
  }

  .answer-content {
    display: flex;
    gap: 12px;

    .answer-text {
      background: #f3f4f6;
      padding: 16px;
      border-radius: 8px;
      margin-bottom: 16px;
      line-height: 1.6;
      color: #666;
      font-size: 14px;
    }

    .formal-answer {
      background: #ffffff;
      padding: 20px;
      border-radius: 8px;
      line-height: 1.8;
      color: #333;
      font-size: 15px;
      a {
        color: #2563eb;
        text-decoration: underline;
      }
      h1,
      h2,
      h3,
      h4,
      h5,
      h6 {
        margin: 1em 0;
        color: #2563eb;
      }

      ul,
      ol {
        padding-left: 2em;
        margin: 1em 0;
      }

      li {
        margin: 0.5em 0;
      }

      code {
        background: #f3f4f6;
        padding: 0.2em 0.4em;
        border-radius: 4px;
        font-family: Monaco, Consolas, monospace;
      }

      pre {
        background: #f3f4f6;
        padding: 1em;
        border-radius: 8px;
        overflow-x: auto;
        margin: 1em 0;

        code {
          background: none;
          padding: 0;
        }
      }
    }

    .content-box {
      flex: 1;
      .thinking-header {
        display: flex;
        align-items: center;
        margin-bottom: 12px;

        img {
          margin-right: 8px;
        }

        .thinking {
          font-weight: bold;
          color: #333;
        }
      }
      .ai-input-wrapper {
        margin-top: 20px;
        position: relative;

        .send-icon {
          cursor: pointer;
          transition: transform 0.2s;
          margin-right: 8px;
          margin-top: 8px;

          &:hover {
            transform: scale(1.1);
          }
        }

        :deep(.el-input__inner) {
          padding-right: 40px;
        }
      }
    }
  }
}
.search-box {
  background: #fff;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);

  .search-title {
    font-size: 14px;
    color: #9ca3af;
    text-align: center;
    margin: 0 0 30px 0;
  }
}
.input-wrapper {
  position: relative;

  .send-icon {
    position: absolute;
    right: 16px;
    bottom: 16px;
    cursor: pointer;
    z-index: 2;

    img {
      transition: transform 0.2s;

      &:hover {
        transform: scale(1.1);
      }
    }
  }
}
:deep(.el-textarea__inner) {
  padding-right: 48px;
}
.ai-search-container {
  max-width: 800px;
  margin: 40px auto;
  padding: 0 20px;

  .header {
    text-align: center;
    margin-bottom: 40px;

    .title {
      display: inline-flex;
      align-items: center;
      position: relative;

      i {
        font-size: 24px;
        color: #409eff;
        margin-right: 8px;
      }

      h1 {
        font-size: 24px;
        color: #409eff;
        margin: 0;
      }

      .beta-tag {
        position: absolute;
        right: -40px;
        top: 0;
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .preset-questions {
    margin-top: 20px;
    background: #fff;
    border-radius: 8px;
    padding: 20px;

    .question-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #909399;
      margin-bottom: 12px;
    }

    .question-item {
      padding: 12px;
      background: #f5f7fa;
      border-radius: 4px;
      margin-bottom: 8px;
      cursor: pointer;
      transition: background 0.3s;

      &:hover {
        background: #ecf5ff;
      }

      i {
        margin-right: 8px;
        color: #409eff;
      }
    }
  }

  .result-box {
    margin-top: 20px;
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .result-header {
      font-weight: bold;
      margin-bottom: 16px;
    }

    .result-content {
      background: #f5f7fa;
      padding: 16px;
      border-radius: 4px;
    }
  }

  .new-search-btn {
    display: block;
    width: 100%;
    margin-top: 20px;
  }

  .footer-text {
    margin-top: auto;
    padding: 20px 0;
    text-align: center;
    color: #909399;
    font-size: 12px;
  }

  .ai-search-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    margin: 0;
    padding: 40px 20px;
    box-sizing: border-box;
  }

  .main-wrapper {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
  }

  .search-box {
    flex: 1;
    min-height: 0;
    background: #fff;
    border-radius: 8px;
    padding: 30px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
    overflow-y: auto;
  }

  .chat-container {
    height: 100%;
    display: flex;
    flex-direction: column;

    .message-list {
      flex: 1;
      min-height: 0;
      overflow-y: auto;
    }
  }
}
.chat-container {
  .message-list {
    .message-item {
      margin-bottom: 20px;

      &.user-message {
        .user-header {
          display: flex;
          align-items: center;
          background-color: #2563eb;
          height: 34px;
          padding: 0 12px;
          border-radius: 4px;
          margin-bottom: 20px;

          img {
            margin-right: 12px;
          }

          span {
            font-size: 14px;
            color: #fff;
          }
        }
      }

      &.ai-message {
        .message-content {
          .thinking-header {
            display: flex;
            align-items: center;
            margin-bottom: 12px;

            img {
              margin-right: 8px;
            }

            .thinking {
              font-weight: bold;
              color: #333;
            }
          }

          .answer-text {
            background: #f3f4f6;
            padding: 16px;
            border-radius: 8px;
            margin-bottom: 16px;
            line-height: 1.6;
            color: #666;
            font-size: 14px;
          }

          .formal-answer {
            background: #ffffff;
            padding: 20px;
            border-radius: 8px;
            line-height: 1.8;
            color: #333;
            font-size: 15px;

            a {
              color: #2563eb;
              text-decoration: underline;
            }

            h1,
            h2,
            h3,
            h4,
            h5,
            h6 {
              margin: 1em 0;
              color: #2563eb;
            }

            ul,
            ol {
              padding-left: 2em;
              margin: 1em 0;
            }

            li {
              margin: 0.5em 0;
            }

            code {
              background: #f3f4f6;
              padding: 0.2em 0.4em;
              border-radius: 4px;
              font-family: Monaco, Consolas, monospace;
            }

            pre {
              background: #f3f4f6;
              padding: 1em;
              border-radius: 8px;
              overflow-x: auto;
              margin: 1em 0;

              code {
                background: none;
                padding: 0;
              }
            }
          }
        }
      }
    }
  }
}
</style>
